package com.example.dqdq.lzyim_asm_tvapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.x;

import com.example.dqdq.lzyim_asm_tvapp.api.API;
import com.example.dqdq.lzyim_asm_tvapp.https.HttpManger;
import com.example.dqdq.lzyim_asm_tvapp.utils.ActivityCollector;
import com.example.dqdq.lzyim_asm_tvapp.utils.EncodingHandler;
import com.google.zxing.WriterException;
import com.umeng.analytics.MobclickAgent;

import java.sql.Timestamp;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class QRcodeActivity extends BaseActivity {

    private ImageView qrCodeImg;
    private Timer timer;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String random;
    private boolean frist=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode);
        ActivityCollector.addActivity(this);

        initView();
    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    private void initView() {
//        int rd = (int) (Math.random() * 100000);
//        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//          random=String.valueOf(rd) + String.valueOf(timestamp.getTime());
        //获取手机唯码
        random = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        WifiInfo info = wifi.getConnectionInfo();

        random+=","+ info.getMacAddress();
        //生成二维码
        try {
            Bitmap qrcodeBitmap = EncodingHandler.createQRCode(random, 500);
            qrCodeImg = (ImageView) findViewById(R.id.qrCodeImg);
            qrCodeImg.setImageBitmap(qrcodeBitmap);
            timer = new Timer();
            timer.schedule(task, 1000, 1000);       // timeTask

        } catch (WriterException e) {
            e.printStackTrace();
        }

    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            x.http().post(HttpManger.getParams(API.USER_DATA_SELECT, "random", random), new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    try {
                        JSONObject obj = new JSONObject(result);
                        Log.e("test", String.valueOf(obj.getBoolean("success")));
                        if (obj.getBoolean("success")) {
                            JSONObject data = obj.getJSONObject("data");
                            preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                            editor = preferences.edit();
                            editor.putInt("id", data.getInt("id"));
                            editor.putString("phone", data.getString("phone"));
                            editor.putString("address", data.getString("address"));
                            editor.putString("name", data.getString("name"));
                            editor.putString("random", data.getString("random"));
                            editor.putString("type", data.getString("typename"));
                            editor.putString("addtime", data.getString("addtime"));
                            editor.putBoolean("firststart", false);
                            editor.putString("identity", data.getString("identity"));
                            editor.putString("purchase", data.getString("purchase"));
                            editor.putString("purchasedate", data.getString("purchasedate"));
                            editor.putString("purchaseprice", data.getString("purchaseprice"));
                            editor.putString("purchasebrand", data.getString("purchasebrand"));
                            editor.putString("purchasemodel", data.getString("purchasemodel"));
                            editor.putString("purchasebarcode", data.getString("purchasebarcode"));
                            editor.putString("factorydate", data.getString("factorydate"));
                            editor.putString("servicedate", data.getString("servicedate"));
                            editor.putString("serviceclass", data.getString("servicename"));

                            editor.putString("serviceengineer", data.getString("serviceengineer"));

                            editor.commit();
                            JPushInterface.setAlias(QRcodeActivity.this, random, new TagAliasCallback() {
                                @Override
                                public void gotResult(int i, String s, Set<String> set) {
                                    if (frist) {
                                        Log.e("setAlias", String.valueOf(i));
                                        if (i==1)
                                        {   editor = preferences.edit();
                                            editor.putBoolean("alias",true);
                                            editor.commit();
                                        }
                                        Toast.makeText(x.app(), "添加成功", Toast.LENGTH_LONG).show();
                                        Intent intent = new Intent(QRcodeActivity.this, MainActivity.class);
                                        startActivity(intent);
                                        finish();
                                        frist=false;
                                        timer.cancel();
                                        return;
                                    }
                                }
                            });
                            timer.cancel();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    //  Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {
                    //   Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onFinished() {

                }
            });
        }
    };

    @Override
    protected void onStop(){
        super.onStop();
        timer.cancel();
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}
